
#include "esp32_com.h"

#if LVGL_IS_ENABLE

#include <Arduino_GFX_Library.h>
Arduino_DataBus *bus = new Arduino_ESP32SPI(ST7789_DC, ST7789_CS, 
                           ST7789_SCK, ST7789_MOSI, ST7789_MISO, ST7789_SPI);
Arduino_GFX *gfx = new Arduino_ST7789(bus, ST7789_RST, ST7789_ROTATION, true, 
                           ST7789_WIDTH, ST7789_HIGHT, 0, 20,  0, 20);

//==========================================================================
void my_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p){
  uint32_t w = (area->x2 - area->x1 + 1);
  uint32_t h = (area->y2 - area->y1 + 1);
  gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&color_p->full, w, h);
  lv_disp_flush_ready(disp);
}

static lv_color_t *disp_buf;
static lv_disp_drv_t disp_drv;
static lv_disp_draw_buf_t draw_buf;
static unsigned long last_ms;
//==========================================================================
void esp32_display_init(void){
  gfx->begin();
  gfx->fillScreen(BLACK);
  pinMode(ST7789_BL, OUTPUT);
  digitalWrite(ST7789_BL, HIGH);
  //-----------------------------------------------------------------------
  lv_init();
  disp_buf = (lv_color_t *)heap_caps_malloc(sizeof(lv_color_t) * ST7789_WIDTH * 10, 
                                            MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  lv_disp_draw_buf_init(&draw_buf, disp_buf, NULL, ST7789_WIDTH * 10);
  lv_disp_drv_init(&disp_drv);
  disp_drv.hor_res = ST7789_HIGHT;
  disp_drv.ver_res = ST7789_WIDTH;
  disp_drv.flush_cb = my_disp_flush;
  disp_drv.draw_buf = &draw_buf;
  lv_disp_drv_register(&disp_drv);
  //-----------------------------------------------------------------------
  last_ms = millis();
}

//==========================================================================
void esp32_display_loop(void){
  lv_timer_handler();
  unsigned long current_ms = millis();
  lv_tick_inc(current_ms - last_ms);
  last_ms = current_ms;
}

#endif
